<?php

namespace app\index\controller;

use think\Controller;

/**
 * Class Index
 * @package app\index\controller
 */
class Index extends Controller
{
    protected $beforeActionList = [
        'verifyLogin' => ['except' => 'logout']
    ];

    protected function verifyLogin()
    {
        if (session('?user')) {
            $this->redirect('info/index');
        }
    }

    /**
     * 用户登录页面
     */
    public function index()
    {
        return view();
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $data = getInputData(['username', 'password']);
        $verify = validateData($data, 'user', 'login');
        if ($verify === true) {
            $user = model('user')->where('username', $data['username'])->find();
            if (!$user) {
                $this->error('登录失败：用户名不存在');
            }
            if (password_verify($data['password'], $user->password)) {
                session('user', $user);
                $this->success('登录成功！', 'info/index');
            } else {
                $this->error('登录失败：密码不正确');
            }
        } else {
            $this->error('登录失败：' . $verify);
        }
    }

    /**
     * 用户注册页面
     */
    public function regist()
    {
        return view();
    }

    /**
     * 用户注册
     */
    public function register()
    {
        $data = getInputData(['username', 'password', 'email', 'nickname']);
        $verify = validateData($data, 'user', 'register');
        if ($verify === true) {
            $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
            $data['avatar'] = 'default.jpg';
            model('user')->save($data);
            $this->success('注册成功！', 'index');
        } else {
            $this->error('注册失败：' . $verify);
        }
    }

    /**
     * 用户登出
     */
    public function logout()
    {
        session('user', null);
        if (session('?user')) {
            $this->error('登出失败！');
        } else {
            $this->success('登出成功！', 'index/index');
        }
    }
}
